package com.itboye.pondteam.pondteam;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hiflying.smartlink.OnSmartLinkListener;
import com.hiflying.smartlink.SmartLinkedModule;
import com.hiflying.smartlink.v7.MulticastSmartLinker;
import com.itboye.pondteam.R;
import com.itboye.pondteam.app.MyApplication;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.SearchDeviceInfo;
import com.itboye.pondteam.db.DBManager;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;

import java.util.Observable;
import java.util.Observer;

import static com.itboye.pondteam.utils.EmptyUtil.getSp;


/**
 * Created by Mr.w on 2017/3/4.
 */

public class DeviceRegisteringActivity extends BaseActivity implements Observer, OnSmartLinkListener {
    TextView btn_next;
    TextView txt_title;
    ImageView img_back;
    String did, uid;
    UserPresenter userPresenter;
    TextView txt_1, txt_2, txt_3;
    ImageView img_finish_1, img_finish_2, img_finish_3;
    ProgressBar progress;
    MyApplication myApp;
    boolean isFindDevice = false;
    RelativeLayout re_1, re_2;
    private MulticastSmartLinker mSnifferSmartLinker;
    private String wifiName, wifiPass;
    private SearchDeviceInfo searchDeviceInfo;
    DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_registering);
        myApp = (MyApplication) getApplication();
        myApp.deviceRegisterUI = this;
        dbManager = new DBManager(this);
        btn_next.setVisibility(View.GONE);
        mSnifferSmartLinker = MulticastSmartLinker.getInstance();
        mSnifferSmartLinker.setOnSmartLinkListener(this);
        txt_title.setText(getString(R.string.add_device));
        did = getIntent().getStringExtra("did");
        uid = getSp(Const.UID);
        wifiName = getIntent().getStringExtra("wifi_name");
        wifiPass = getIntent().getStringExtra("wifi_pass");
        isBusy = false;
        txt_1.setText("");
        //先通过did查询设备的状态
        userPresenter = new UserPresenter(this);
        showProgressDialog(getString(R.string.peizhiing), true);
        //开始 smartLink
        try {
            mSnifferSmartLinker.start(getApplicationContext(), wifiPass,
                    wifiName);
        } catch (Exception e) {
            closeProgressDialog();
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                String msg = btn_next.getText().toString();
                if (msg.equals(getString(R.string.wancheng))) {
                    myApp.addPondDeviceUI.finish();
                    myApp.deviceListActivityUI.getMyDeviceList();
                    finish();
                }
                if (msg.equals(getString(R.string.research))) {
                    isFindDevice = false;
                    showProgressDialog(getString(R.string.peizhiing), true);
                    try {
                        txt_1.setText("");
                        mSnifferSmartLinker.start(getApplicationContext(), wifiPass,
                                wifiName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if (isFindDevice == false || searchDeviceInfo == null) {
                        MAlert.alert(getString(R.string.deviceid_error));
                        return;
                    }
                    if (hasAdd(searchDeviceInfo.getDid())) {
                        MAlert.alert(getString(R.string.hasAdd));
                        return;
                    }
                    re_1.setVisibility(View.VISIBLE);
                    progress.setVisibility(View.VISIBLE);
                    userPresenter.addDevice(uid, searchDeviceInfo.getDid(), "PondTeam");
                }
                break;
            case R.id.img_back:
                finish();
                break;

        }
    }

    /**
     * 检测是否已经添加过该设备
     *
     * @param did
     * @return
     */
    private boolean hasAdd(String did) {
        boolean isAdd = false;
        if (myApp != null) {
            if (myApp.deviceListActivityUI != null) {
                if (myApp.deviceListActivityUI.arrayList != null) {
                    for (int i = 0; i < myApp.deviceListActivityUI.arrayList.size(); i++) {
                        if (did.equals(myApp.deviceListActivityUI.arrayList.get(i).getDid())) {
                            isAdd = true;
                            break;
                        } else {
                            isAdd = false;
                        }
                    }
                }
            }
        }
        return isAdd;
    }

    @Override
    public void update(Observable o, Object data) {

        ResultEntity resultEntity = handlerError(data);
        if (resultEntity != null) {
            if (resultEntity.getCode() != 0) {
                isFindDevice = false;
                txt_1.setText(getString(R.string.getDetail_fail) + "");
                btn_next.setText(getString(R.string.research));
                MAlert.alert(resultEntity.getMsg());
                return;
            } else if (resultEntity.getEventType() == UserPresenter.adddevice_success) {
                progress.setVisibility(View.GONE);
                img_finish_2.setVisibility(View.VISIBLE);
                img_finish_3.setVisibility(View.VISIBLE);
                re_2.setVisibility(View.VISIBLE);
                txt_2.setText(getString(R.string.register_success));
                txt_3.setText(resultEntity.getData() + "");
                btn_next.setText(getString(R.string.wancheng));
                dbManager.insertDeviceData(searchDeviceInfo.getDid(), searchDeviceInfo.getPwd(),getSp(Const.UID));
            } else if (resultEntity.getEventType() == UserPresenter.adddevice_fail) {
                txt_3.setText(resultEntity.getData() + "");
            }
        }
    }

    @Override
    public void onLinked(SmartLinkedModule smartLinkedModule) {

    }

    @Override
    public void onCompleted() {
        try {
            closeProgressDialog();
        } catch (Exception e) {

        }
        btn_next.setVisibility(View.VISIBLE);
        isFindDevice = true;
        //值为1表示在线
        img_finish_1.setVisibility(View.VISIBLE);
        txt_1.setText(getString(R.string.search_success));
        btn_next.setText(getString(R.string.next));
    }

    @Override
    public void onTimeOut() {
        try {
            closeProgressDialog();
        } catch (Exception e) {

        }
        btn_next.setVisibility(View.VISIBLE);
        isFindDevice = false;
        txt_1.setText("TimeOut");
        btn_next.setText(getString(R.string.research));
        MAlert.alert("TimeOut");
    }

    boolean isBusy;

    public void findNewDeviceInfo(SearchDeviceInfo deviceInfo) {

        this.searchDeviceInfo = deviceInfo;
        // 查空
        if (deviceInfo == null) {
            return;
        }
        //还未配置成功
        if (!isBusy) {
            return;
        }
        isBusy = false;
        did = deviceInfo.getDid();
        img_finish_1.setVisibility(View.VISIBLE);
        // 只处理正在配置中的状态
//        if (!mBusy) {
//            return;
//        }
        // 停止配置
//        stopConfig();
        // 添加设备
//        mApp.addDevice(deviceInfo);
        // 提示新设备
        isFindDevice = true;
        try {
            closeProgressDialog();
        } catch (Exception e) {

        }
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("消息");
        alert.setMessage("发现新设备 DID : \n" + deviceInfo.getDid());
        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 停止配置
//                        mApp.mSmartConfigUi = null;
//                        Intent intent = new Intent(ActivityStepThree.this, DeviceActivity.class);
//                        startActivity(intent);
//                        finish();
            }
        });
        alert.show();
    }
}
